<?php

class BaggingBetinaModel{
	private $db;
	private $subbagian;
	
	private $validColumn;
	private $data;

	private $result;

	private $sort_by;
	private $sort_order;

	private $search_keyword;
	private $search_field;

	private $limit;
	
	function BaggingBetinaModel($dbObject){
		$this->subbagian 	= 'bagging_betina';		
		$this->db 			= $dbObject;

		$this->validColumn  = array(
			'no_individu', 
			'tgl_bagging', 
			'varietas',
			
			'no_tandan'
			);
		
		// settting up configuration
		if(($this->start=$this->getGET('start')) == NULL)
			$this->start = 0;

		$this->sort_by 			= $this->getGET('sort_by');
		$this->sort_order 		= $this->getGET('sort_order');
		$this->search_keyword	= $this->getGET('search_keyword');
		$this->search_field		= $this->getGET('search_field');

		if(($this->limit=$this->getGET('limit')) == NULL)
			$this->limit = 50;					
	}
	
	private function getGET($param){
		if( isset( $_GET[$param] ) && $_GET[$param] != '' )
			return $_GET[$param];
		else
			return NULL;
	}
	
	public function countAll(){
		$where = $this->prepareWhereClause();
		$q = "SELECT COUNT(*) FROM `caramel_operational`.`bagging_betina` $where";
		
		$this->total_record = $this->db->get_var($q);
		
		return $this->total_record;
	}	
	
	private function prepareWhereClause(){
		$where = '';
		if( $this->search_keyword && $this->search_field ){
			switch($this->search_field){
				case 'no_tandan':
					$where = "WHERE `id` IN (SELECT `bagging_id` FROM `caramel_operational`.`bagging_betina_no_tandan` WHERE `no_tandan`='".$this->search_keyword."')";
					break;
				default:
					$where = "WHERE ".$this->search_field."='".$this->search_keyword."'";
			}
		}
		
		return $where;
	}	
	
	private function getDetailBagging($id){
		$q = "SELECT `no_tandan` FROM `caramel_operational`.`bagging_betina_no_tandan` WHERE `bagging_id`='".$id."'";
	
		$result = array();
		$r = $this->db->get_results($q, ARRAY_A);
		if( $r )	
			foreach($r as $j) $result[] = $j;
		
		return $result;
	}
	
	public function search(){			
		$where = $this->prepareWhereClause();
		// get data
		if( $this->sort_by )
			$q = "
			SELECT `id`, `tgl_bagging`, `no_individu`, `varietas` 
			FROM  `caramel_operational`.`bagging_betina` $where
			ORDER BY ".$this->sort_by." ".$this->sort_order." LIMIT ".$this->start.",".$this->limit."";
		else
			$q = "
			SELECT `id`, `tgl_bagging`, `no_individu`, `varietas` 
			FROM  `caramel_operational`.`bagging_betina` $where ORDER BY `tgl_bagging` DESC
			LIMIT ".$this->start.",".$this->limit."";

		$this->result = $this->db->get_results($q, ARRAY_A);
		// detail
		if( count($this->result) > 0 ){
			foreach($this->result as &$r){
				$r['no_tandan']  = $this->getDetailBagging($r['id']);
			}
		}
		
		return $this->result;
	}

	public function getResult(){
		return $this->result;
	}
	
	function format($data){
		$result = array();
		foreach($this->validColumn as $v){
			if( isset($data[$v]) )
				$result[$v] = $data[$v];
			else
				$result[$v] = NULL;
		}
		
		return $result;
	}
	
	private function insertBagging(){
		$dataBagging   = array();
		$baggingColumn = array(
			'no_individu', 
			'tgl_bagging', 
			'varietas'
		);
		
		// copy dari $data ke $dataBagging
		foreach($baggingColumn as $c){
			$dataBagging[$c] = $this->data[$c];
		}
		
		$qHeader = "(`".implode($baggingColumn, "`, `")."`)";
		$qBody   = "('".implode($dataBagging, "', '")."')";
		
		$query = "INSERT INTO `caramel_operational`.`bagging_betina` ".$qHeader." VALUES ".$qBody;
		$this->db->query($query);
		
		$id = $this->db->get_var("SELECT MAX(`Id`) FROM `caramel_operational`.`bagging_betina`");
		
		return $id;
	}
	
	private function insertNoTandan($id){
		$dataNoTandan = array();
		$noTandanColumn = array(
			'no_tandan'
		);
		
		// copy dari $data ke $dataNoTandan
		foreach($noTandanColumn as $c){
			$dataNoTandan[$c] = $this->data[$c];
		}
		
		if( count($dataNoTandan['no_tandan']) > 0 ){
		
			$qHeader = "(`bagging_id`, `no_tandan`)";			
			$query   = "INSERT INTO `caramel_operational`.`bagging_betina_no_tandan` ".$qHeader." VALUES ";
			$temp    = '';
			// looping through all material
			for($i=0; $i<count($dataNoTandan['no_tandan']); $i++){			
				$qBody   = "('".$id."', '".$dataNoTandan['no_tandan'][$i]."')";
				$temp[]  = $qBody;
			}
			
			$query .= implode($temp, ",").';';
			
			$this->db->query($query);
		}
	}
	
	
	function put($data){		
		$this->data	= $this->format($data);// buang field2 yang tidak dibutuhkan
		
		if( $this->isExist() == FALSE ){				
			// bagging
			$id = $this->insertBagging();
			// tandan
			$this->insertNoTandan($id);					
		}
		else{
			return INSERT_FAIL_DUPLICATE;
		}		
	}
	
	function isExist(){	
		$query = "SELECT COUNT(*) FROM `caramel_operational`.`bagging_betina` WHERE `no_individu`='".$this->data['no_individu']."' AND `tgl_bagging`='".$this->data['tgl_bagging']."'";	
		$count = $this->db->get_var($query);
		
		if( $count > 0 )
			return TRUE;	
			
		return FALSE; // tidak ada data yang dicari... no duplicate		
	}
    
    public function delete($id){
       // delete bagging
       $this->deleteBagging($id);
       // delete no tandan
       $this->deleteNoTandan($id);
    }
    
    private function deleteBagging($id){
        $q = "
        DELETE FROM `caramel_operational`.`bagging_betina` 
        WHERE `id`='$id'";
        
        $this->db->query($q);
    }
    
    private function deleteNoTandan($bagging_id){
        $q = "
        DELETE FROM `caramel_operational`.`bagging_betina_no_tandan` 
        WHERE `bagging_id`='$bagging_id'";
        
        $this->db->query($q);
    }
    
    private function getNoTandanById($bagging_id){
        $data = array();
        $q = "
            SELECT `no_tandan` 
            FROM `caramel_operational`.`bagging_betina_no_tandan`
            WHERE `bagging_id`='$bagging_id'
            ";
        $data = $this->db->get_results($q, ARRAY_A);
        
        if( $data != NULL && count($data) > 0 ){            
            return $data;
        }
        else{
            return NULL;
        }   
    }
    
    public function getById($id){
        $q = "SELECT * FROM `caramel_operational`.`bagging_betina` WHERE `id`='$id'";
        $r = $this->db->get_results($q, ARRAY_A);
        
        if( is_array($r) && count($r) > 0 ){
            // main data..
            $data = array_pop($r);
            
            // no tandan
            $data['no_tandan']  = $this->getNoTandanById($id);
            
            return $data;
        }
        else{
            return NULL;
        }
    }
    
    public function editById($data, $id){
        $valid = $this->getById($id);
        if( $valid == NULL ){
            return EDIT_ID_INVALID;
        }
        
        // populate data
        $this->data	= $this->format($data);
        
        $q = "
            UPDATE `caramel_operational`.`bagging_betina`
            SET 
                `no_individu`='".$this->data['no_individu']."',
                `tgl_bagging`='".$this->data['tgl_bagging']."',
                `varietas`='".$this->data['varietas']."'
            WHERE `id`='$id'
            ";
        if( $this->db->query($q) ){
            // hapus (refresh)
            // no tandan
            $this->deleteNoTandan($id);            
            
            // kemudian insert semuanya
            // kelompok
			$this->insertNoTandan($id);
            
            return EDIT_OK;
        }
        else{
            return EDIT_FAIL;
        }        
    }
}
?>